package com.mall.order.services;

import com.mall.commons.tool.exception.BizException;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 *  ciggar
 * create-date: 2019/7/30-上午10:05
 */
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

	@Autowired
	OrderMapper orderMapper;

	@Autowired
	OrderItemMapper orderItemMapper;

	@Autowired
	OrderShippingMapper orderShippingMapper;

	@Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

	@Autowired
	StockMapper stockMapper;


	/**
	 * 创建订单的处理流程
	 *
	 * @param request
	 * @return
	 */
	@Override
	public CreateOrderResponse createOrder(CreateOrderRequest request) {
		CreateOrderResponse response = new CreateOrderResponse();

		try {
			// 检查请求参数是否合法
			request.requestCheck();
		} catch (ValidateException e) {
			log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}

		try {
			//创建pipeline对象
			TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

			//启动pipeline
			invoker.start(); //启动流程（pipeline来处理）

			//获取处理结果
			AbsTransHandlerContext context = invoker.getContext();

			//把处理结果转换为response
			response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
			System.out.println("response = " + response);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		return response;
	}

	@Override
	public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
		// 取消订单的逻辑：a.修改订单状态为已取消7，b.恢复恢复锁定的商品库存
		CancelOrderResponse response = new CancelOrderResponse();

		try {
			// 检查请求参数是否合法
			request.requestCheck();

			String orderId = request.getOrderId();

			Order order = new Order();
			order.setOrderId(orderId);
			order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);

			// 根据orderId更新订单的状态
			int affectedRows = orderMapper.updateByPrimaryKeySelective(order);
			if (affectedRows != 1) {
				throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
			}

			// 根据订单id查询出订单商品关联信息
			Example orderItemExample = new Example(OrderItem.class);
			orderItemExample.createCriteria()
					.andEqualTo("orderId", orderId);
			List<OrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample);

			// 由于订单取消，需要恢复锁定的商品库存
			for (OrderItem orderItem : orderItems) {
				Stock stock = new Stock();
				stock.setItemId(orderItem.getItemId());
				stock.setStockCount(orderItem.getNum().longValue());
				stock.setLockCount(-orderItem.getNum());

				stockMapper.updateStock(stock);
			}


			response.setCode(OrderRetCode.SUCCESS.getCode());
			response.setMsg(OrderRetCode.SUCCESS.getMessage());
		} catch (Exception e) {
			log.info("OrderCoreServiceImpl#cancelOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
			//e.printStackTrace();
		}

		return response;
	}

	@Override
	public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {
		DeleteOrderResponse response = new DeleteOrderResponse();

		try {
			// 检查请求参数是否合法
			request.requestCheck();

			String orderId = request.getOrderId();

			// 如果订单的状态是未支付状态0，则需要先取消订单，恢复冻结的商品库存
			Order order = orderMapper.selectByPrimaryKey(orderId);
			if (order.getStatus() == 0) {
				CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
				cancelOrderRequest.setOrderId(orderId);
				cancelOrder(cancelOrderRequest);
			}

			// 根据orderId删除订单
			int affectedRows = orderMapper.deleteByPrimaryKey(orderId);
			if (affectedRows != 1) {
				throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
			}

			// 根据orderId删除order_item
			Example orderItemExample = new Example(OrderItem.class);
			orderItemExample.createCriteria()
					.andEqualTo("orderId", orderId);
			int affectedRows2 = orderItemMapper.deleteByExample(orderItemExample);
			if (affectedRows2 < 1) {
				throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
			}

			// 根据orderId删除order_shipping
			int affectedRows3 = orderShippingMapper.deleteByPrimaryKey(orderId);
			if (affectedRows3 < 1) {
				throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
			}

			response.setCode(OrderRetCode.SUCCESS.getCode());
			response.setMsg(OrderRetCode.SUCCESS.getMessage());
		} catch (Exception e) {
			log.info("OrderCoreServiceImpl#deleteOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
			//e.printStackTrace();
		}

		return response;
	}

	@Override
	public PayOrderSuccessResponse payOrderSuccess(PayOrderSuccessRequest request) {
		PayOrderSuccessResponse payOrderSuccessResponse = new PayOrderSuccessResponse();

		try {
			request.requestCheck();

			Date currentDate = new Date();
			String orderId = request.getOrderId();
			//1.修改tb_order表中，订单的status，update_time，payment_time
			Order order = new Order();
			order.setOrderId(orderId);
			order.setStatus(OrderConstants.ORDER_STATUS_PAYED);
			order.setPaymentTime(currentDate);
			order.setUpdateTime(currentDate);
			int updateOrderStatusAffectedRows = orderMapper.updateByPrimaryKeySelective(order);
			System.out.println("updateOrderStatusAffectedRows = " + updateOrderStatusAffectedRows);

			//2.扣减订单中所有商品的锁定库存
			// 1)查询出订单中的所有商品
			// 2)扣减订单中每个商品的锁定库存
			Example example = new Example(OrderItem.class);
			example.createCriteria()
					.andEqualTo("orderId", orderId);
			List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
			for (OrderItem orderItem : orderItems) {
				Stock stock = new Stock();
				stock.setItemId(orderItem.getItemId());
				stock.setLockCount(-orderItem.getNum());
				stock.setStockCount(new Long(0));
				stockMapper.updateStock(stock);
			}

			// 设置成功响应
			payOrderSuccessResponse.setCode(OrderRetCode.SUCCESS.getCode());
			payOrderSuccessResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
		} catch (Exception e) {
			log.info("OrderCoreServiceImpl#payOrderSuccess Occur Exception: " + e);
			ExceptionProcessorUtils.wrapperHandlerException(payOrderSuccessResponse, e);
			//e.printStackTrace();
		}

		return payOrderSuccessResponse;
	}

}
